package cn.tedu.knows.auth.service;

import cn.tedu.knows.commons.model.Permission;
import cn.tedu.knows.commons.model.Role;
import cn.tedu.knows.commons.model.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

//将这个类保存到Spring容器
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private RestTemplate restTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获得用户名对应的用户对象
        String url="http://sys-service/v1/auth/user?username={1}";
        User user=restTemplate.getForObject(url,User.class,username);
        if(user==null){
            // 如果user对象是null,表示用户输入的用户名在数据库中不存在
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 用户存在,开始查询用户的所有权限和角色
        url="http://sys-service/v1/auth/permissions?id={1}";
        // 当Ribbon请求的目标方法返回List类型时
        // 要使用该List返回值的泛型类型的数组来接收
        Permission[] permissions=restTemplate.getForObject(
                url,Permission[].class,user.getId());
        url="http://sys-service/v1/auth/roles?id={1}";
        Role[] roles=restTemplate.getForObject(
                url,Role[].class,user.getId());
        String[] auth=new String[permissions.length+ roles.length];
        int i=0;
        for(Permission p:permissions){
            auth[i++]=p.getName();
        }
        for(Role r:roles){
            auth[i++]=r.getName();
        }
        // 构建UserDetails对象
        UserDetails u= org.springframework.security.core.userdetails
                .User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .build();
        // 最后别忘了返回u
        return u;
    }
}
